<?php

/**
 * Phonebook object
 *
 * @author DungNQ7
 */
if (class_exists('PhoneBook') == false) {

    class Phonebook {

        private $prefix = 'fpt_';
        private $version = '0.1';
        private $errorContacts = array();
        private $ids = array();

        public function __construct() {

            // localization
            add_action('init', array(&$this, 'enableLocalization'));

            // create phonebook custom post type            
            add_action('init', array(&$this, 'createCustomPostType'));
//            add_filter('post_updated_messages', array(&$this, 'modifyUpdateMessage'));
//            add_action('contextual_help', array(&$this, 'modifyHelpText'), 10, 3);
            add_action('init', array(&$this, 'createCustomTaxonomy'));


            if (is_admin()) { // admin actions
                add_action('admin_menu', array(&$this, 'addMenu'));
                add_action('add_meta_boxes', array(&$this, 'addCustomFields'));
                add_action('save_post', array(&$this, 'saveCustomFields'), 0, 1);
                add_action('restrict_manage_posts', array(&$this, 'addCustomFilter'));
                add_filter('parse_query', array(&$this, 'addCustomFilterQuery'));
            } else {
                // non-admin enqueues, actions, and filters

                wp_enqueue_script('jquery.highlight', plugins_url('jquery.highlight-4.js', __FILE__), array('jquery'), $this->version, true);
                wp_register_style($this->prefix . 'style', plugins_url('style.css', __FILE__));
                wp_enqueue_style($this->prefix . 'style');
            }

            // add short code
            add_shortcode('contact_search_box', array(&$this, 'getSearchBox'));
        }

        public function enableLocalization() {
            $langDir = dirname(plugin_basename(__FILE__)) . '/languages/';
            /* echo '<!--';
              var_dump($langDir);
              echo '-->'; */
            load_plugin_textdomain('fpt-phonebook', false, $langDir);
        }

        public function createCustomPostType() {
            $labels = array(
                'name' => _x('Contacts', 'post type general name', 'fpt-phonebook'),
                'singular_name' => _x('contact', 'post type singular name', 'fpt-phonebook'),
                'add_new' => _x('Add New Contact', 'contact', 'fpt-phonebook'),
                'add_new_item' => __('Add New Contact', 'fpt-phonebook'),
                'edit_item' => __('Edit Contact', 'fpt-phonebook'),
                'new_item' => __('New Contact', 'fpt-phonebook'),
                'all_items' => __('All Contacts', 'fpt-phonebook'),
                'view_item' => __('View Contact', 'fpt-phonebook'),
                'search_items' => __('Search Contact', 'fpt-phonebook'),
                'not_found' => __('No contacts found', 'fpt-phonebook'),
                'not_found_in_trash' => __('No contacts found in Trash', 'fpt-phonebook'),
                'parent_item_colon' => '',
                'menu_icon' => plugins_url('/kaddressbook.png', __FILE__),
                'menu_name' => __('Contacts', 'fpt-phonebook')
            );
            $args = array(
                'labels' => $labels,
                'public' => true,
                'publicly_queryable' => true,
                'show_ui' => true,
                'show_in_menu' => true,
                'query_var' => true,
                'rewrite' => array('slug' => _x('contact', 'URL slug', 'fpt-phonebook')),
                'capability_type' => 'post',
                'has_archive' => true,
                'hierarchical' => false,
                'menu_position' => null,
                'supports' => array('title')
            );
            register_post_type('contact', $args);
        }


        public function createCustomTaxonomy() {
            // create a new taxonomy
            $labels = array(
                'name' => _x('Organization', 'taxonomy general name', 'fpt-phonebook'),
                'singular_name' => _x('Organization', 'taxonomy singular name', 'fpt-phonebook'),
                'search_items' => __('Search Organization', 'fpt-phonebook'),
                'all_items' => __('All Organization', 'fpt-phonebook'),
                'parent_item' => __('Parent Organization', 'fpt-phonebook'),
                'parent_item_colon' => __('Parent Organization:', 'fpt-phonebook'),
                'edit_item' => __('Edit Organization', 'fpt-phonebook'),
                'update_item' => __('Update Organization', 'fpt-phonebook'),
                'add_new_item' => __('Add New Organization', 'fpt-phonebook'),
                'new_item_name' => __('New Organization name', 'fpt-phonebook'),
                'menu_name' => __('Organization'),
            );

            register_taxonomy('organization', array('contact'), array(
                'hierarchical' => true,
                'labels' => $labels,
                'show_ui' => true,
                'query_var' => true,
                'rewrite' => array('slug' => 'organization'),
            ));



            $labels = array(
                'name' => _x('Location', 'taxonomy general name', 'fpt-phonebook'),
                'singular_name' => _x('Location', 'taxonomy singular name', 'fpt-phonebook'),
                'search_items' => __('Search Location', 'fpt-phonebook'),
                'all_items' => __('All Location', 'fpt-phonebook'),
                'parent_item' => __('Parent Location'),
                'parent_item_colon' => __('Parent Location:', 'fpt-phonebook'),
                'edit_item' => __('Edit Location', 'fpt-phonebook'),
                'update_item' => __('Update Location', 'fpt-phonebook'),
                'add_new_item' => __('Add New Location', 'fpt-phonebook'),
                'new_item_name' => __('New Location name', 'fpt-phonebook'),
                'menu_name' => __('Location', 'fpt-phonebook'),
            );

            register_taxonomy('location', array('contact'), array(
                'hierarchical' => true,
                'labels' => $labels,
                'show_ui' => true,
                'query_var' => true,
                'rewrite' => array('slug' => 'location'),
            ));



            $labels = array(
                'name' => _x('Job Title', 'taxonomy general name', 'fpt-phonebook'),
                'singular_name' => _x('Job Title', 'taxonomy singular name', 'fpt-phonebook'),
                'search_items' => __('Search Job Title', 'fpt-phonebook'),
                'all_items' => __('All Job Title', 'fpt-phonebook'),
                'parent_item' => __('Parent Job Title', 'fpt-phonebook'),
                'parent_item_colon' => __('Parent Job Title:', 'fpt-phonebook'),
                'edit_item' => __('Edit Job Title', 'fpt-phonebook'),
                'update_item' => __('Update Job Title', 'fpt-phonebook'),
                'add_new_item' => __('Add New Job Title', 'fpt-phonebook'),
                'new_item_name' => __('New Job Title', 'fpt-phonebook'),
                'menu_name' => __('Job Title'),
            );

            register_taxonomy('job-title', array('contact'), array(
                'hierarchical' => true,
                'labels' => $labels,
                'show_ui' => true,
                'query_var' => true,
                'rewrite' => array('slug' => 'job-title'),
            ));
        }

        public function addCustomFilter() {
            global $typenow;
            global $wp_query;
            if ($typenow == 'contact') {
                $taxonomy = 'organization';
                $organization_taxonomy = get_taxonomy($taxonomy);
                wp_dropdown_categories(array(
                    'show_option_all' => sprintf(__("Show All %s"), $organization_taxonomy->label),
                    'taxonomy' => $taxonomy,
                    'name' => __('organization'),
                    'orderby' => 'name',
                    'selected' => $wp_query->query['organization'],
                    'hierarchical' => true,
                    'depth' => 3,
                    'show_count' => false, // Show # listings in parens
                    'hide_empty' => false // Don't show businesses w/o listings
                ));
            }
        }

        public function addCustomFilterQuery($query) {
            global $pagenow;
            global $typenow;
            if ($pagenow == 'edit.php' && $typenow == 'contact') {
                $filters = get_object_taxonomies($typenow);
                foreach ($filters as $tax_slug) {
                    $var = &$query->query_vars[$tax_slug];
                    if (isset($var)) {
                        $term = get_term_by('id', $var, $tax_slug);
                        $var = $term->slug;
                    }
                }
            }
        }

        public function addMenu() {
            add_menu_page('Phonebook Settings', 'Phonebook', 'administrator', 'phonebook', array(&$this, 'displaySetting'), plugins_url('/address_book.png', __FILE__));

            /**
             * Sub menu for function
             * Import
             * Permission
             * Merge Orgnaization, location, 
             */
            //add_submenu_page('phonebook', 'Import Data', 'Import', 'manage_options', 'phonebook-import', array(&$this, 'displayImport'));
            add_submenu_page('edit.php?post_type=contact', 'Import Data', 'Import', 'edit_posts', 'phonebook-import', array(&$this, 'displayImport'));
            add_submenu_page('edit.php?post_type=contact', 'Extract Data', 'Extract', 'edit_posts', 'phonebook-extract', array(&$this, 'displayExtract'));
            add_submenu_page('phonebook', 'Reset Data', 'Reset', 'manage_options', 'phonebook-reset', array(&$this, 'resetData'));

            add_submenu_page('phonebook', 'Extract', 'Export', 'manage_options', 'phonebook-extract', array(&$this, 'displayExtract'));
             add_submenu_page('phonebook', 'Anpha ', 'Anpha', 'manage_options', 'phonebook-anpha', array(&$this, 'displayContactSortAnpha'));
              add_submenu_page('phonebook', 'Favorite', 'Favorite', 'manage_options', 'phonebook-export', array(&$this, 'displayFavoriteContact'));
               


        }

        public function displaySetting() {
            // action here
        }

        public function displayExtract() {
            if (!current_user_can('edit_posts')) {
                wp_die(__('You do not have sufficient permissions to access this page.', 'fpt-phonebook'));
            }

            print('
<div class="wrap">
    ' . screen_icon('options-general') .
                    '<h2>' . __('Extract contact data', 'fpt-phonebook') . '</h2>
			
    <form method="POST" action="' . plugin_dir_url(__FILE__) . 'extract.php' . '" enctype="multipart/form-data">
        <table class="form-table">
                <tr valign="top">
                        <th scope="row">
                                <label for="data">
                                ' . __('Extract contact data', 'fpt-phonebook') . ':
                                </label>
                        </th>
                        <td>
                                <input type="file" name="data" /><br />
                                <p class="description">' . __('You can upload file to extract contact data', 'fpt-phonebook') . '</p>
                        </td>
                </tr>                
                <tr>
                        <th scope="row">
                                
                        </th>
                        <td>
                                <input type="hidden" name="update_settings" value="Y" />
                                <input type="submit" value="Extract" class="button-primary" /> 
                        </td>
                </tr>
        </table>

                                        
    </form>
</div>
        ');
        }

// end displayExtract

        public function displayImport() {
            if (!current_user_can('edit_posts')) {
                wp_die(__('You do not have sufficient permissions to access this page.', 'fpt-phonebook'));
            }

            if (isset($_POST["update_settings"]) && $_POST["update_settings"] = 'Y') {
                // remove data if choice
                if (($organiaztion_id = $_POST['remove_contacts_from_organization_id']) > 0) {
                    $args = array(
                        'post_type' => 'contact',
                        'tax_query' => array(
                            array(
                                'taxonomy' => 'organization',
                                'field' => 'term_id',
                                'terms' => $organiaztion_id
                            )
                        )
                    );
                    $contacts = get_posts($args);
                    while (count($contacts) > 0) {
                        foreach ($contacts as $contact) {
                            wp_delete_post($contact->ID);
                        }
                        $contacts = get_posts($args);
                    }
                }
                // import new data
                if (isset($_FILES['data']['tmp_name']) && file_exists($_FILES['data']['tmp_name'])) {
                    $this->importData(file_get_contents($_FILES['data']['tmp_name']));
                }
            }

            printf('
<div class="wrap">
    ' . screen_icon('options-general') .
                    '<h2>' . __('Import contact data', 'fpt-phonebook') . '</h2>
			
    <form method="POST" action="" enctype="multipart/form-data">
        <table class="form-table">
                <tr valign="top">
                        <th scope="row">                        
                        </th>
                        <td>                                
                                <p class="description">' . __('Please download template file at ', 'fpt-phonebook') . '<a href="' . plugin_dir_url(__FILE__) . 'contacts.xml' . '">' . __('here') . '</a></p>
                        </td>
                </tr>
                <tr valign="top">
                        <th scope="row">
                                <label for="data">
                                ' . __('Upload contact data', 'fpt-phonebook') . ':
                                </label>
                        </th>
                        <td>
                                <input type="file" name="data" /><br />
                                <p class="description">' . __('You can upload file to import contact data', 'fpt-phonebook') . '</p>
                        </td>
                </tr>
                <tr valign="top">
                        <th scope="row">
                                <label for="data">
                                ' . __('Remove all contact from organization', 'fpt-phonebook') . ':
                                </label>
                        </th>
                        <td>
                                %1$s
                                <p class="description">' . __('Please select organization you want to remove all contact', 'fpt-phonebook') . '</p>
                        </td>
                </tr>
                <tr>
                        <th scope="row">
                                
                        </th>
                        <td>
                                <input type="hidden" name="update_settings" value="Y" />
                                <input type="submit" value="Import" class="button-primary" /> 
                        </td>
                </tr>
        </table>

                                        
    </form>
</div>
        ', wp_dropdown_categories('name=remove_contacts_from_organization_id&show_option_none=---&show_count=1&orderby=name&echo=0&depth=5&hierarchical=1&hide_empty=0&taxonomy=organization'));
        }

        // only administrator running
        public function resetData() {
            if (!current_user_can('manage_options')) {
                wp_die(__('You do not have sufficient permissions to access this page.', 'fpt-phonebook'));
            }

            if (isset($_POST["update_settings"]) && $_POST["update_settings"] = 'Y') {
                // do reset data

                global $wpdb;
                // delete all organization, location, job-title
                $terms = $wpdb->get_results("select term_id, taxonomy from {$wpdb->term_taxonomy} where taxonomy in ('organization', 'location', 'job-title') limit 5");
                while (is_array($terms) && count($terms) > 0) {
                    foreach ($terms as $term) {
                        wp_delete_term($term->term_id, $term->taxonomy);
                    }
                    $terms = $wpdb->get_results("select term_id, taxonomy from {$wpdb->term_taxonomy} where taxonomy in ('organization', 'location', 'job-title') limit 5");
                }

                // delete all contact            
                $contacts = get_posts(array('post_type' => 'contact'));
                while (count($contacts) > 0) {
                    foreach ($contacts as $contact) {
                        wp_delete_post($contact->ID);
                    }
                    $contacts = get_posts(array('post_type' => 'contact'));
                }
            }

            printf('
<div class="wrap">
    ' . screen_icon('options-general') .
                    '<h2>' . __('Reset contact data', 'fpt-phonebook') . '</h2>
			
    <form method="POST" action="" enctype="multipart/form-data">
        <table class="form-table">
                <tr valign="top">
                        <th scope="row">
                                <label for="data">
                                ' . __('Reset all contact data') . ':
                                </label>
                        </th>
                        <td>
                                <input type="checkbox" name="reset" value=1 /><br />
                                <p class="description">' . __('If you tick on checkbox and click Reset button, all contact data will be deleted.', 'fpt-phonebook') . '</p>
                        </td>
                </tr>
                <tr>
                        <th scope="row">
                                
                        </th>
                        <td>
                                <input type="hidden" name="update_settings" value="Y" />
                                <input type="submit" value="Reset" class="button-primary" /> 
                        </td>
                </tr>
        </table>

                                        
    </form>
</div>
        ');
        }
     
        public function extractData($xml) {
            global $wpdb;
            /**
             * format contact data from xml
             * - First name
             * - Last name
             * - Job title
             * - Email
             * - Unit
             * - Department
             * - Company
             * - City
             * - Phone
             * - Ext
             * - Mobile
             *-  Group        
             * Ignore first row as title
             */
            $xml = mb_convert_encoding($xml, 'HTML-ENTITIES', 'UTF-8');
            //$xml = str_replace(' ss:', ' ', $xml);
            //var_dump($xml);
            $doc = new DOMDocument('1.0', 'utf-8');
            @$doc->loadHTML($xml);
            $xpath = new DOMXPath($doc);
            //die($doc->saveXML());
            $contacts = array();
            $contactNodes = $xpath->query('//worksheet//row');
            //var_dump($contactNodes);
            //die();
            $notfound = 0;
            $xml = '';
            if ($contactNodes->length > 0 && $contactNodes->length <= 1000) {
                // loog to discover, ignore first row
                for ($i = 1; $i < $contactNodes->length; $i++) {
                    $infoNodes = $xpath->query($contactNodes->item($i)->getNodePath() . '/cell');
                    //var_dump($infoNodes->length);
                    if ($infoNodes->length > 0) {
                        $info = array();
                        $index = 1;
                        foreach ($infoNodes as $cell) {
//                        echo '<pre>';
//                        var_dump($cell->getAttribute('index'));
//                        echo '</pre>';
                            $ind = (int) $cell->getAttribute('index');
                            if ($ind > 0)
                                $index = $ind;

                            switch ($index) {
                                case 1:
                                    $info['firstname'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    $info['group'] = substr($info['firstname'], 0, 1);
                                    break;
                                case 2:
                                    $info['lastname'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;    
                                case 3:
                                    $info['jobtitle'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 4:
                                    $info['email'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 5:
                                    $info['company'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 6:
                                    $info['department'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 7:
                                    $info['unit'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 8:
                                    $info['city'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 9:
                                    $info['address'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 10:
                                    $info['phone'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 11:
                                    $info['ext'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 12:
                                    $info['mobile'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                            }
                            $index += 1;
                        }
                        // check exit contact on database to remove node                        
                        if (is_email($info['email'])) {
                            $query = $wpdb->prepare("select meta_id from $wpdb->postmeta where meta_key = '_email' and meta_value = %s", $info['email']);
                            $id = (int) $wpdb->get_var($query);
                            if ($id > 0) {
                                // remove node
                                // $contactNodes->item($i)->parentNode->removeChild($contactNodes->item($i));
                            } else {
                                $xml = sprintf('
<Row ss:AutoFitHeight="0">
    <Cell><Data ss:Type="String">%1$s</Data></Cell>
    <Cell><Data ss:Type="String">%2$s</Data></Cell>
    <Cell><Data ss:Type="String">%3$s</Data></Cell>
    <Cell><Data ss:Type="String">%4$s</Data></Cell>
    <Cell><Data ss:Type="String">%5$s</Data></Cell>
    <Cell><Data ss:Type="String">%6$s</Data></Cell>
    <Cell><Data ss:Type="String">%7$s</Data></Cell>
    <Cell><Data ss:Type="String">%8$s</Data></Cell>    
    <Cell><Data ss:Type="String">%9$s</Data></Cell>
    <Cell><Data ss:Type="String">%10$s</Data></Cell>
    <Cell><Data ss:Type="String">%11$s</Data></Cell>
    <Cell><Data ss:Type="String">%12$s</Data></Cell>
</Row> 
                                     ', $info['firstname'], //1
                                        $info['lastname'], //2
                                        $info['jobtitle'], //3
                                        $info['email'], //4
                                        $info['company'], //5
                                        $info['department'], //6
                                        $info['unit'], //7
                                        $info['city'], //8
                                        $info['address'], //9
                                        $info['phone'], //10
                                        $info['ext'], //11
                                        $info['mobile']//12
                                );

                                $notfound++;
                            }
                        }
                    }
                }
            }



            // export xml to download
            if ($notfound == 0) {
                return '';
            } else {

                $xml = '
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>Dung Nguyen Quang 7 (FIM HN)</Author>
  <LastAuthor>Dung Nguyen Quang 7 (FIM HN)</LastAuthor>
  <Created>2013-04-16T03:30:04Z</Created>
  <Version>12.00</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>11835</WindowHeight>
  <WindowWidth>18960</WindowWidth>
  <WindowTopX>120</WindowTopX>
  <WindowTopY>135</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="11" ss:ExpandedRowCount="3" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15">
   <Column ss:AutoFitWidth="0" ss:Width="111"/>
   <Column ss:AutoFitWidth="0" ss:Width="113.25"/>
   <Column ss:AutoFitWidth="0" ss:Width="69" ss:Span="8"/>
   <Row ss:AutoFitHeight="0">
    <Cell><Data ss:Type="String">Tên</Data></Cell>
    <Cell><Data ss:Type="String">Họ</Data></Cell>
    <Cell><Data ss:Type="String">Chức danh</Data></Cell>
    <Cell><Data ss:Type="String">E-Mail Address</Data></Cell>
    <Cell><Data ss:Type="String">Công ty</Data></Cell>
    <Cell><Data ss:Type="String">Đơn vị</Data></Cell>
    <Cell><Data ss:Type="String">Bộ phận</Data></Cell>
    <Cell><Data ss:Type="String">Nơi làm việc</Data></Cell>
    <Cell><Data ss:Type="String">Địa chỉ</Data></Cell>
    <Cell><Data ss:Type="String">Máy tổng đài</Data></Cell>
    <Cell><Data ss:Type="String">Máy lẻ</Data></Cell>
    <Cell><Data ss:Type="String">Di động</Data></Cell>
   </Row>
   ' . $xml . '
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <PageSetup>
    <Header x:Margin="0.3"/>
    <Footer x:Margin="0.3"/>
    <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
   </PageSetup>
   <Unsynced/>
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>2</ActiveRow>
     <ActiveCol>5</ActiveCol>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet2">
  <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15">
   <Row ss:AutoFitHeight="0"/>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <PageSetup>
    <Header x:Margin="0.3"/>
    <Footer x:Margin="0.3"/>
    <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
   </PageSetup>
   <Unsynced/>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet3">
  <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15">
   <Row ss:AutoFitHeight="0"/>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <PageSetup>
    <Header x:Margin="0.3"/>
    <Footer x:Margin="0.3"/>
    <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
   </PageSetup>
   <Unsynced/>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>

                    ';

                /*
                  $xml = $doc->saveXML();
                  $xml = preg_replace('/.+<body>(.*?)<\/body>.+/siu', '$1', $xml);
                  $xml = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?>' . $xml;
                 * 
                 */
                //die($xml);
                return $xml;
            }
        }

        private function importData($xml) {
            /**
             * format contact data from xml
             * - First name
             * - Last name
             * - Job title
             * - Email
             * - Unit
             * - Department
             * - Company
             * - City
             * - Phone
             * - Ext
             * - Mobile         
             * Ignore first row as title
             */
            $xml = mb_convert_encoding($xml, 'HTML-ENTITIES', 'UTF-8');
            //$xml = str_replace(' ss:', ' ', $xml);
            //var_dump($xml);
            $doc = new DOMDocument('1.0', 'utf-8');
            @$doc->loadHTML($xml);
            $xpath = new DOMXPath($doc);

            $contacts = array();
            $contactNodes = $xpath->query('//worksheet//row');
            $success = 0;
            $error = 0;
            if ($contactNodes->length > 0 && $contactNodes->length <= 1000) {
                // loog to discover, ignore first row
                for ($i = 1; $i < $contactNodes->length; $i++) {
                    $infoNodes = $xpath->query($contactNodes->item($i)->getNodePath() . '/cell');
                    //var_dump($infoNodes->length);
                    if ($infoNodes->length > 0) {
                        $info = array();
                        $index = 1;
                        foreach ($infoNodes as $cell) {
//                        echo '<pre>';
//                        var_dump($cell->getAttribute('index'));
//                        echo '</pre>';
                            $ind = (int) $cell->getAttribute('index');
                            if ($ind > 0)
                                $index = $ind;

                            switch ($index) {
                                case 1:
                                    $info['firstname'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    $info['group'] = substr($info['firstname'], 0, 1);
                                    break;
                                case 2:
                                    $info['lastname'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 3:
                                    $info['jobtitle'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 4:
                                    $info['email'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 5:
                                    $info['company'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 6:
                                    $info['department'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 7:
                                    $info['unit'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 8:
                                    $info['city'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 9:
                                    $info['address'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 10:
                                    $info['phone'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 11:
                                    $info['ext'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                                case 12:
                                    $info['mobile'] = $this->cleanString($xpath->query($cell->getNodePath() . '//data')->item(0)->nodeValue);
                                    break;
                            }
                            $index += 1;
                        }

                        // add contact to database
                        if (is_email($info['email']) && $this->addContact($info) == true) {
                            $success++;
                        } else {
                            $error++;
                        }
                    }
                }
            }

            // display results 

            if ($success > 0) {
                printf('<div id="message" class="updated"><p>%s</p></div>', sprintf(__('Insert succeess %d contacts'), $success)
                );
            }

            if ($contactNodes->length <= 0 || $contactNodes->length >= 1000) {
                printf('<div id="message" class="error"><p>%s</p></div>', sprintf(__('Please import from 1 - 1000 contact at time.'), $success)
                );
            }

            if ($error > 0) {
                printf('<div id="message" class="error"><p>%s</p>', sprintf(__('Error %d contacts, please check email of contact'), $error)
                );
                print('<pre>');
                print_r($this->errorContacts);
                print('</pre>');
                print('</div>');
            }
        }

        private function cleanString($str) {
            $str = preg_replace('/[\s\n]+/', ' ', $str);
            $str = trim($str);
            return $str;
        }

        private function addContact($contact) {

            global $wpdb;

            // check exit email address to update 
            // one persion can have more than one email
            /**
             * format contact data from xml is an array
             * - First name
             * - Last name
             * - Job title
             * - Email
             * - Unit
             * - Department
             * - Company
             * - City
             * - Phone
             * - Ext
             * - Mobile
             * - Group
             * Ignore first row as title
             */
            // find all organization or create

            $companyId = 0;
            if ($contact['company'] != '') {
                //$company = get_term_by('slug', sanitize_title($contact['company']), 'organization');
                //$query = $wpdb->prepare("select * from $wpdb->term_taxonomy where parent = 0 and  ")
//            $company = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id 
//                WHERE tt.taxonomy = %s AND t.slug = %s AND tt.parent = %d LIMIT 1", 'organization', $contact['company'], 0));

                $slug = sanitize_title($contact['company']);
                $company = get_term_by('slug', $slug, 'organization');
                if ($company) {
                    $companyId = $company->term_id;
                } else {
                    $term = wp_insert_term(
                            $contact['company'], // the term 
                            'organization', // the taxonomy
                            array('parent' => 0, 'slug' => $slug)
                    );
                    //var_dump($term);
                    if (is_array($term) && isset($term['term_id'])) {
                        $companyId = $term['term_id'];
                    }
                }
            }

            // find department
            $departmentId = 0;
            if ($contact['department'] != '' && $companyId > 0) {
                //$department = get_term_by('slug', sanitize_title($contact['department']), 'organization');
//            $department = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id 
//                WHERE tt.taxonomy = %s AND t.name = %s AND tt.parent = %d LIMIT 1", 'organization', $contact['department'], $companyId));

                $slug = sanitize_title($contact['company'] . ' ' . $contact['department']);
                $department = get_term_by('slug', $slug, 'organization');
                if ($department) {
                    $departmentId = $department->term_id;
                } else {
                    $term = wp_insert_term(
                            $contact['department'], // the term 
                            'organization', // the taxonomy
                            array('parent' => $companyId, 'slug' => $slug)
                    );

                    if (is_array($term) && isset($term['term_id'])) {
                        $departmentId = $term['term_id'];
                    }
                }
            }

            // find unit
            $unitId = 0;
            if ($contact['unit'] != '' && $departmentId > 0) {
                //$unit = get_term_by('slug', sanitize_title($contact['unit']), 'organization');
//            $unit = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id 
//                WHERE tt.taxonomy = %s AND t.name = %s AND tt.parent = %d LIMIT 1", 'organization', $contact['unit'], $departmentId));
                $slug = sanitize_title($contact['company'] . ' ' . $contact['department'] . ' ' . $contact['unit']);
                $unit = get_term_by('slug', $slug, 'organization');
                if ($unit) {
                    $unitId = $unit->term_id;
                } else {
                    $term = wp_insert_term(
                            $contact['unit'], // the term 
                            'organization', // the taxonomy
                            array('parent' => $departmentId, 'slug' => $slug)
                    );

                    if (is_array($term) && isset($term['term_id'])) {
                        $unitId = $term['term_id'];
                    }
                }
            }

            // find all location or create if not exists
            $cityId = 0;
            if ($contact['city'] != '') {
                //$city = get_term_by('slug', sanitize_title($contact['city']), 'location');
//            $city = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id 
//                WHERE tt.taxonomy = %s AND t.name = %s AND tt.parent = %d LIMIT 1", 'location', $contact['city'], 0));
                //var_dump($city);
                //die();

                $slug = sanitize_title($contact['city']);
                $city = get_term_by('slug', $slug, 'location');
                if ($city) {
                    $cityId = $city->term_id;
                } else {
                    $term = wp_insert_term(
                            $contact['city'], // the term 
                            'location', // the taxonomy
                            array('parent' => 0, 'slug' => $slug)
                    );

                    if (is_array($term) && isset($term['term_id'])) {
                        $cityId = $term['term_id'];
                    }
                }
            }


            // find all location or create if not exists
            $addressId = 0;
            if ($contact['address'] != '' && $cityId > 0) {
                //$address = get_term_by('slug', sanitize_title($contact['address']), 'location');
//            $address = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id 
//                WHERE tt.taxonomy = %s AND t.name = %s AND tt.parent = %d LIMIT 1", 'location', $contact['address'], 0));
                //var_dump($city);
                //die();
                $slug = sanitize_title($contact['city'] . ' ' . $contact['address']);
                $address = get_term_by('slug', $slug, 'location');
                if ($address) {
                    $addressId = $address->term_id;
                } else {
                    $term = wp_insert_term(
                            $contact['address'], // the term 
                            'location', // the taxonomy
                            array('parent' => $cityId, 'slug' => $slug)
                    );

                    if (is_array($term) && isset($term['term_id'])) {
                        $addressId = $term['term_id'];
                    }
                }
            }

            // find job title or create if not exists
            $jobTitleId = 0;

            if ($contact['jobtitle'] != '') {
                $jobTitle = get_term_by('slug', sanitize_title($contact['jobtitle']), 'job-title');
                //var_dump($city);
                //die();
                if ($jobTitle) {
                    $jobTitleId = $jobTitle->term_id;
                } else {
                    $term = wp_insert_term(
                            $contact['jobtitle'], // the term 
                            'job-title', // the taxonomy
                            array(
                        'parent' => 0
                            )
                    );

                    if (is_array($term) && isset($term['term_id'])) {
                        $jobTitleId = $term['term_id'];
                    }
                }
            }

            $post = array(
                'post_title' => $contact['lastname'].' '.$contact['firstname'],
                'post_content' => $contact['lastname'].' '.$contact['firstname'] . ' ' . $contact['email'] . ' ' . $contact['mobile'] . ' ' . $contact['fullname'] . ' ' . $contact['phone'] . ' ' . $contact['ext'],
                'post_type' => 'contact',
                'post_status' => 'publish'
            );

            // check exit with email
            if ($contact['email'] != "") {
                global $wpdb;
                $post_id = $wpdb->get_var($wpdb->prepare("select post_id from {$wpdb->postmeta} where meta_key = '_email' and meta_value = %s ", $contact['email']));

                if ($post_id > 0) {
                    $insert_id = $post_id;
                    // update contact
                    $post['ID'] = $post_id;
                    wp_update_post($post);
                } else {
                    $insert_id = wp_insert_post($post);
                }
            } else {
                $this->errorContacts[] = $contact;
            }


            //var_dump($insert_id);
            if ($insert_id > 0) {
                // insert post meta 
                if ($contact['firstname'] != ''){
                    update_post_meta($insert_id, '_firstname', $contact['firstname']);
                    update_post_meta($insert_id, '_group', substr($contact['firstname'], 0, 1));
                }   

                if ($contact['lastname'] != '')
                    update_post_meta($insert_id, '_lastname', $contact['lastname']);
                if ($contact['email'] != '')
                    update_post_meta($insert_id, '_email', $contact['email']);
                if ($contact['phone'] != '')
                    update_post_meta($insert_id, '_phone', $contact['phone']);
                if ($contact['ext'] != '')
                    update_post_meta($insert_id, '_ext', $contact['ext']);
                if ($contact['mobile'] != '')
                    update_post_meta($insert_id, '_mobile', $contact['mobile']);

                // insert more taxonomy
                if ($cityId > 0) {
                    wp_set_object_terms($insert_id, (int) $cityId, 'location');
                }

                if ($addressId > 0) {
                    wp_set_object_terms($insert_id, (int) $addressId, 'location');
                }

                if ($companyId > 0) {
                    wp_set_object_terms($insert_id, (int) $companyId, 'organization');
                }

                if ($departmentId > 0) {
                    wp_set_object_terms($insert_id, (int) $departmentId, 'organization', true);
                }

                if ($unitId > 0) {
                    wp_set_object_terms($insert_id, (int) $unitId, 'organization', true);
                }

                if ($jobTitleId > 0) {
                    wp_set_object_terms($insert_id, (int) $jobTitleId, 'job-title', true);
                }

                return true;
            } else {
                return false;
            }
        }

        public function getSearchBox() {
            $q = stripslashes(trim($_GET['q'])) != __('Enter your keyword', 'fpt-phonebook') ? stripslashes(trim($_GET['q'])) : '';
            $o = (int) stripslashes(trim($_GET['o'])) > 0 ? (int) stripslashes(trim($_GET['o'])) : 0;
            $l = (int) stripslashes(trim($_GET['l'])) > 0 ? (int) stripslashes(trim($_GET['l'])) : 0;
            $p = (int) stripslashes(trim($_GET['pagenum'])) > 0 ? (int) stripslashes(trim($_GET['pagenum'])) : 1;

            //var_dump($o);
            $html = sprintf('

<div> <a onClick="loyalTest()">LoyalTest</a></div>            

<script>
function loyalTest(){
    //alert("LoyalTest running");
    jQuery("#dialog").dialog("open");
}
</script>

<form method="GET"  action="" enctype="multipart/form-data" class="contact-search-box" id="target">
    <table width="100%%">
        <tr>
            <td width="30%%"><label for="q">' . __('Your keyword', 'fpt-phonebook') . '</label></td>
            <td width="60%%"><input type="text" name="q" value="%1$s" style="width:100%%; height:95%%; padding:5px;" /></td>
            <td width="10%%"><input type="submit" value="' . __('Find', 'fpt-phonebook') . '" /></td>
        </tr>
        <tr>
            <td></td>
            <td>' . __('Enter name/email/mobile/ip phone... to searching', 'fpt-phonebook') . '</td>            
            <td></td>
        </tr>
        <tr>
            <td>' . __('Organization', 'fpt-phonebook') . '</td>
            <td>%2$s</td>            
            <td></td>
        </tr>
        <tr>
            <td>' . __('Location', 'fpt-phonebook') . '</td>
            <td>%3$s</td>            
            <td></td>
        </tr>
    </table>
</form>
<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the icon.</p>
</div>
<script>
    jQuery("input[name=q]").blur(function(){
        if (this.value == "") {
            this.value = "' . __('Enter your keyword', 'fpt-phonebook') . '";
        }
    })
        
    jQuery("input[name=q]").focus(function(){
        if (this.value == "' . __('Enter your keyword', 'fpt-phonebook') . '") {
            this.value = "";
        }
    })
    jQuery("#target").submit(function() {
        
            jQuery("#dialog").dialog("open");
            return false;
        
  });
</script>
', ($q != '') ? esc_attr($q) : '', // 1
                    wp_dropdown_categories('show_option_none=---&show_count=0&hierarchical=1&depth=1&taxonomy=organization&echo=0&orderby=slug&name=o&&selected=' . $o), // 2
                    wp_dropdown_categories('show_option_none=---&show_count=0&hierarchical=1&depth=1&taxonomy=location&echo=0&orderby=slug&name=l&&selected=' . $l)
            );




            // display search results
            $favorite = false;
            $html .= $this->getSearchResultHTML($q, $o, $l, $p, $s = 20, $favorite);
        //}
        //else $html = sprintf(" Bạn hãy điền đây đủ thông tin, để được tìm kiếm");
    return $html;
    
    }


        public function getSearchResultVCard($q = '', $o = 0, $l = 0, $p = 1, $s = 20) {
            $data = $this->getSearchResult($q, $o, $l, $p, $s);

            $html = '';
            if (is_array($data) && count($data) > 0) {
                foreach ($data as $contact) {
                    $organization = strip_tags(get_the_term_list($contact['id'], 'organization', '', ', ', ''));
                    $organization = $this->remove_vietnamese_accents($organization);
                    $location = strip_tags(get_the_term_list($contact['id'], 'location', '', ', ', ''));
                    $location = $this->remove_vietnamese_accents($location);
                    $jobTitle = strip_tags(get_the_term_list($contact['id'], 'job-title', '', ', ', ''));
                    $jobTitle = $this->remove_vietnamese_accents($jobTitle);

                    $html .= sprintf('
BEGIN:VCARD
VERSION:3.0
N:charset=UTF-8
%2$s
END:VCARD  

                    ', "", //1
                            trim(
                                    ($contact['firstname'] ? sprintf('FN:%1$s', $this->remove_vietnamese_accents($contact['firstname'])) . "\n" : '') .
                                    ($contact['lastname'] ? sprintf('FN:%1$s', $this->remove_vietnamese_accents($contact['lastname'])) . "\n" : '') .
                                    ($jobTitle ? sprintf('TITLE:%1$s', $jobTitle) . "\n" : '' ) .
                                    ($contact['phone'] ? sprintf('TEL;WORK;VOICE:%1$s', $contact['phone']) . "\n" : '' ) .
                    
                                    ($contact['mobile'] ? sprintf('TEL;TYPE=CELL:%1$s', $contact['mobile']) . "\n" : '' ) .
                                    ($contact['email'] ? sprintf('EMAIL;TYPE=INTERNET:%1$s', $contact['email']) . "\n" : '' ) .
                                    ($organization ? sprintf('ORG:%1$s', $organization) . "\n" : '' ) .
                                    ($location ? sprintf('ADR;TYPE=WORK:%1$s', $location) . "\n" : '')
                            )
                    );

                    $html = trim($html) . "\n";
                }
            }

            return $html;
        }

        private function getSearchResultHTML($q = '', $o = 0, $l = 0, $p = 1, $s = 20, $more) {
            if(is_array($more)){
                $anpha = $more[0];
                var_dump($anpha);
                $data = $this->getSearchResultAnpha($anpha);
            }else if ($more == 1) {
                $data = $this->getFavoriteContact();
            }else if($more == 0){
                $data = $this->getSearchResult($q, $o, $l, $p, $s);
            }
            $html = '';            
            if (is_array($data) && count($data) > 0) {
                $s=count($data);
                foreach ($data as $contact) {
                    $organization = strip_tags(get_the_term_list($contact['id'], 'organization', '', ', ', ''));
                    $location = strip_tags(get_the_term_list($contact['id'], 'location', '', ', ', ''));
                    $jobTitle = strip_tags(get_the_term_list($contact['id'], 'job-title', '', ', ', ''));
                    if($contact['favorite']==true)
                        $favorite = "checked";
                    $html .= sprintf('
                        <table class="contact-search-results" cellpadding=5>
                            <tr valign=top>
                                <td width="138">
                                    %1$s
                                </td>
                                <td>
                                    %2$s
                                    %3$s
                                    <input type="checkbox" name="favorite" id="stt" value="%4$s" %5$s > %6$s
                                </td>
                            </tr>
                            </table>
                            
                        

                    ',  get_avatar($contact['email'], 128), 
                            ($contact['firstname'] ? sprintf('<p>%1$s: %2$s</p>', __('First name', 'fpt-phonebook'), $contact['firstname']) : '') .
                            ($contact['lastname'] ? sprintf('<p>%1$s: %2$s</p>', __('Last name', 'fpt-phonebook'), $contact['lastname']) : '') .
                            ($jobTitle ? sprintf('<p>%1$s: %2$s</p>', __('Job Title', 'fpt-phonebook'), $jobTitle) : '' ) .
                            ($contact['phone'] ? sprintf('<p>%1$s: %2$s</p>', __('Phone', 'fpt-phonebook'), $contact['phone']) : '' ) .
                            ($contact['ext'] ? sprintf('<p>%1$s: %2$s</p>', __('Ext (IP Phone)', 'fpt-phonebook'), $contact['ext']) : '' ) .
                            ($contact['mobile'] ? sprintf('<p>%1$s: %2$s</p>', __('Mobile', 'fpt-phonebook'), $contact['mobile']) : '' ) .
                            ($contact['email'] ? sprintf('<p>%1$s: <a href="mailto:%2$s">%2$s</a></p>', __('Email', 'fpt-phonebook'), $contact['email']) : '' ) .
                            ($organization ? sprintf('<p>%1$s: %2$s</p>', __('Organization', 'fpt-phonebook'), $organization) : '' ) .
                            ($location ? sprintf('<p>%1$s: %2$s</p>', __('Location', 'fpt-phonebook'), $location) : ''), current_user_can('editor') ? sprintf('<a href="%2$s">%1$s</a>', __('Edit this contact'), get_edit_post_link($contact['id'])) : ''    
                    ,
                    $contact['id'],
                    $favorite, 
                    __('Add my contact', 'fpt-phonebook')
                    );      
                }
            }
            $html.='<script>
                        jQuery("input[name=favorite]").click(function(){
                            var post_id = "";
                            var data;
                            post_id = jQuery(this).val();
                            //var isChecked = jQuery("input[name=favorite]:checkbox").is("checked") ? 1:0;
                            
                            data = {"post_id": post_id};
                            jQuery.ajax({
                                url:"'.plugin_dir_url(__FILE__).'process.php",
                                type:"post",
                                data:data,
                                async: true,
                                success: function(result){
                                    jQuery(".results").html(result);
                                }
                            })
                        });
                            
                    </script>';

            if ($html == '') {
                $html .= sprintf('<h2>%1$s</h2>', __('Not found any contacts', 'fpt-phonebook'));
            } else {
                // get total contacts
                $total = (int) $this->getSearchTotalContact();
                $num_of_pages = ceil($total / $s);

                $page_links = paginate_links(array(
                    'base' => add_query_arg('pagenum', '%#%'),
                    'format' => '',
                    'prev_text' => __('&laquo;', 'fpt-phonebook'),
                    'next_text' => __('&raquo;', 'fpt-phonebook'),
                    'total' => $num_of_pages,
                    'current' => $p
                ));

                if ($total > 0) {
                    $html = sprintf('<div class="result-msg">%s</div>', sprintf(__('About %s results', 'fpt-phonebook'), number_format($total, 0))) . $html;

                    // display export link only admin
                    if (current_user_can('manage_options')) {
                        $html = sprintf('<div class="download">%s</div>', sprintf('<a href="%1$s">%2$s</a>', plugin_dir_url(__FILE__) . sprintf('export.php?q=%1$s&o=%2$s&l=%3$s&p=%4$s&s=%5$s&f=%6$s', $q, $o, $l, $p, $s, 'vcard'), //
                                                sprintf(__('Download %s results as vCards', 'fpt-phonebook'), number_format($s, 0)) //
                                )) . $html;
                    }                    
                }

                if ($page_links != '') {
                    $html .= sprintf('<div class="paginate">%s</div>', $page_links);
                }

                // add hightlight scripts
                $html .= '<script type="text/javascript">jQuery(document).ready(function($) {
                        $(".contact-search-results").highlight("' . esc_attr($q) . '");                        
                    });</script>';
            }
            return $html;
        }

        public function getSearchResult($q = '', $o = 0, $l = 0, $p = 1, $s = 20) {
            global $wpdb;
            global $query_string;
            $size = $s;

            //die($query_string);
            $html = '';

            $args = array(
                'post_type' => 'contact',
                'post_status' => 'publish',
                'posts_per_page' => $size,
                'paged' => $p,
                'order' => 'ASC',
                'orderby' => 'title');

            if ($q != '') {
                $args['s'] = $q;
            }

            //var_dump($o);

            $args['tax_query'] = array();
            if ($o > 0) {
                $args['tax_query'][] = array(
                    'taxonomy' => 'organization',
                    'field' => 'id',
                    'terms' => (int) $o
                );
            }

            if ($l > 0) {
                $args['tax_query'][] = array(
                    'taxonomy' => 'location',
                    'field' => 'id',
                    'terms' => (int) $l
                );
            }

            //var_dump($args);

            $data = array();
            if (is_array($args) && count($args) > 0) {
                $query = new WP_Query($args);
                $this->search_found_total_contacts = (int) $query->found_posts;
                // Loop
                while ($query->have_posts()):
                    $query->next_post();
                    $id = $query->post->ID;
                    $user_id = get_current_user_id();
                    $favoriteContacts = get_user_meta($user_id,'fptFavoriteContact');
                    
                    if(in_array($id, $favoriteContacts)){
                        $data[] = array(
                            'id' => $id,
                            'email' => get_post_meta($id, '_email', true),
                            'firstname' => get_post_meta($id, '_firstname', true),
                            'lastname' => get_post_meta($id, '_lastname', true),
                            'phone' => get_post_meta($id, '_phone', true),
                            'ext' => get_post_meta($id, '_ext', true),
                            'mobile' => get_post_meta($id, '_mobile', true),
                        
                            
                        );
                    }else{
                        $data[] = array(
                        'id' => $id,
                        'email' => get_post_meta($id, '_email', true),
                        'firstname' => get_post_meta($id, '_firstname', true),
                        'lastname' => get_post_meta($id, '_lastname', true),
                        'phone' => get_post_meta($id, '_phone', true),
                        'ext' => get_post_meta($id, '_ext', true),
                        'mobile' => get_post_meta($id, '_mobile', true),
                    );
                    }

                endwhile;
            }
            return $data;
        }

        private function getSearchTotalContact() {
            return $this->search_found_total_contacts;
        }

        private function get_breadcrumb($id) {

            $post = get_post($id);
            $trail = '';
            //$page_title = get_the_title($post->ID);

            if ($post->post_parent) {
                $parent_id = $post->post_parent;

                while ($parent_id) {
                    $page = get_page($parent_id);
                    $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '"»' . get_the_title($page->ID) . '</a> » ';
                    $parent_id = $page->post_parent;
                }

                $breadcrumbs = array_reverse($breadcrumbs);
                foreach ($breadcrumbs as $crumb)
                    $trail .= $crumb;
            }
            $trail .= '';
            return $trail;
        }

        public function addCustomFields() {
            add_meta_box(
                    'phonebook_custom_fields', __('Phone book custom fields'), array(&$this, 'displayCustomFieldsMetaBox'), 'contact', 'normal', 'high'
            );
        }

        public function displayCustomFieldsMetaBox() {
            global $post;
            //echo '<input type="hidden" name="phonebook_meta_box_nonce" value= "' . wp_create_nonce(basename(__FILE__)) . '"/>';

            $firstname = get_post_meta($post->ID, '_firstname', true);
            $lastname = get_post_meta($post->ID, '_lastname', true);
            $email = get_post_meta($post->ID, '_email', true);
            $phone = get_post_meta($post->ID, '_phone', true);
            $mobile = get_post_meta($post->ID, '_mobile', true);
            $ext = get_post_meta($post->ID, '_ext', true);

            printf(' 
                    <table class="form-table">
                        <tr>
                            <td width="20%%">' . __('First name', 'fpt-phonebook') . '</td><td><input type="text" name="_firstname" size="50" value="' . $firstname . '"/></td>
                        </tr>   
                        <tr>
                            <td width="20%%">' . __('Last name', 'fpt-phonebook') . '</td><td><input type="text" name="_lastname" size="50" value="' . $lastname . '"/></td>
                        </tr>
                        <tr>
                            <td>' . __('Email', 'fpt-phonebook') . '</td><td><input type="text" name="_email" size="50" value="' . $email . '"/></td>
                        </tr>
                        <tr>
                            <td>' . __('Mobile', 'fpt-phonebook') . '</td><td><input type="text" name="_mobile" size="20" value="' . $mobile . '"/></td>
                        </tr>
                        <tr>
                            <td>' . __('Phone', 'fpt-phonebook') . '</td><td><input type="text" name="_phone" size="20" value="' . $phone . '"/></td>
                        </tr>
                        <tr>
                            <td>' . __('Ext', 'fpt-phonebook') . '</td><td><input type="text" name="_ext" size="5" value="' . $ext . '"/></td>
                        </tr>
                    </table>
                ');
        }

        public function saveCustomFields($post_id = 0) {
            if (!$post_id || in_array($post_id, $this->ids)) {
                return $post_id;
            }

            $this->ids[$post_id] = $post_id; // flag to save post one time

            $content = ''; // update for search
            if (isset($_POST['_firstname'])) {
                update_post_meta($post_id, '_firstname', $_POST['_firstname']);
                update_post_meta($post_id, '_group', substr($_POST['_firstname'], 0, 1));
                $content .= $_POST['_firstname'] . "\t";
            }
             if (isset($_POST['_lastname'])) {
                update_post_meta($post_id, '_lastname', $_POST['_lastname']);
                $content .= $_POST['_lastname'] . "\t";
            }

            if (isset($_POST['_email'])) {
                update_post_meta($post_id, '_email', $_POST['_email']);
                $content .= $_POST['_email'] . "\t";
            }
            if (isset($_POST['_phone'])) {
                update_post_meta($post_id, '_phone', $_POST['_phone']);
                $content .= $_POST['_phone'] . "\t";
            }
            if (isset($_POST['_mobile'])) {
                update_post_meta($post_id, '_mobile', $_POST['_mobile']);
                $content .= $_POST['_mobile'] . "\t";
            }
            if (isset($_POST['_ext'])) {
                update_post_meta($post_id, '_ext', $_POST['_ext']);
                $content .= $_POST['_ext'] . "\t";
            }
            if ($content != '' && $post_id > 0) {
                global $wpdb;
                $title = $_POST['_firstname']." ".$_POST['_lastname'];
                $wpdb->update($wpdb->posts, array('post_content' => $content, 'post_title' => $title), array('ID' => $post_id));

                //$data = array('ID' => $post_id, 'post_content' => $content);
                //remove_action('save_post', array(&$this, 'saveCustomFields'));
                //wp_update_post($data);
                //add_action('save_post', array(&$this, 'saveCustomFields'), 0, 1);
            }

            return $post_id;
        }


        private function remove_vietnamese_accents($str) {
            $accents_arr = array(
                "à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă",
                "ằ", "ắ", "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề",
                "ế", "ệ", "ể", "ễ",
                "ì", "í", "ị", "ỉ", "ĩ",
                "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ",
                "ờ", "ớ", "ợ", "ở", "ỡ",
                "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
                "ỳ", "ý", "ỵ", "ỷ", "ỹ",
                "đ",
                "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă",
                "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
                "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
                "Ì", "Í", "Ị", "Ỉ", "Ĩ",
                "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ",
                "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
                "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
                "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
                "Đ"
            );

            $no_accents_arr = array(
                "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
                "a", "a", "a", "a", "a", "a",
                "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
                "i", "i", "i", "i", "i",
                "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o",
                "o", "o", "o", "o", "o",
                "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
                "y", "y", "y", "y", "y",
                "d",
                "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
                "A", "A", "A", "A", "A",
                "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
                "I", "I", "I", "I", "I",
                "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O",
                "O", "O", "O", "O", "O",
                "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
                "Y", "Y", "Y", "Y", "Y",
                "D"
            );

            return str_replace($accents_arr, $no_accents_arr, $str);
        }
        





        public function getEmailUser(){
            $current_user = wp_get_current_user();
            $user_email  = $current_user->user_email ;
            return $user_email ;
        }
        public function getPostID(){
            $user_email  = $this->getEmailUser();
            $args = array(
            'posts_per_page'   => 1,
            'offset'           => 0,
            'orderby'          => 'post_date',
            'order'            => 'DESC',
            'meta_value'       => $user_email,
            'post_type'        => 'contact',
            'post_status'      => 'publish',
            'suppress_filters' => true );
            $post = get_posts($args);
            $post_id = $post->ID;
            return $post_id;  
        }
        /*
        Thong tin User
        */
        public function infoUser(){
            $post_id = $this->getPostID();
            $objUser = get_post($post_id);
        }
        public function checkUser(){
            $post_id = $this->getPostID();
            $email = get_post_meta($post_id,'_email', true);
            $firstname = get_post_meta($post_id,'_firstname', true);
            $lastname = get_post_meta($post_id,'_lastname', true);
            $mobile = get_post_meta($post_id,'_mobile', true);
            
            if($email == null || $firstname == null || $lastname == null || $mobile ==null){
                $show = 0;
            }
            else $show = 1;
            return $show;
        }
    

        public function displayFavoriteContact(){
            $html = '<h2> My Contact</h2>';
            $more = 1;
            $html.= $this->getSearchResultHTML($q = '', $o = 0, $l = 0, $p = 1, $s = 20, $more);
            print_r($html);
        }

        public function getFavoriteContact(){
            $data = $this->arrayUserFavorite();
            $contacts = array();
            if(is_array($data)){
                foreach ($data as $objData) {
                    $id = $objData;
                    $favorite = true;
                    $contacts[] = $this->getContact( $id, $favorite);
            }
            array_multisort($contacts, SORT_ASC);
            return $contacts;
            }
        }
        public function displayContactSortAnpha(){
            $html = '<h2> Contact, Sort by Anpha </h2>';
            $html.= sprintf('
                <a></a>

                ');
            $more = array("đ");
            var_dump($more);
            $html.= $this->getSearchResultHTML($q = '', $o = 0, $l = 0, $p = 1, $s = 20, $more);
            print_r($html);
        }
        public function getSearchResultAnpha($anpha){   
            $ANPHA = array(
                "a", "à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă",
                "ằ", "ắ", "ặ", "ẳ", "ẵ", "e", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề",
                "ế", "ệ", "ể", "ễ",
                "i", "ì", "í", "ị", "ỉ", "ĩ",
                "o", "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ",
                "ờ", "ớ", "ợ", "ở", "ỡ",
                "u", "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
                "ỳ", "ý", "ỵ", "ỷ", "ỹ",
                "d", "đ",
                "A", "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă",
                "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
                "E", "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
                "I", "Ì", "Í", "Ị", "Ỉ", "Ĩ",
                "O", "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ",
                "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
                "U", "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
                "Y", "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
                "D", "Đ",
                "b", "B", "c", "C", "f", "F", "g", "G", "j", "J", "k", "K", "m", "M", 
                "n", "N", "o", "O", "l", "L", "p", "P", "q", "Q","r", "R", "s", "S",
                "t", "T", "u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z",           
            );
            
            if(in_array( $anpha, $ANPHA)){
                $args = array(
                    'posts_per_page'   => -1,
                    'offset'           => 0,
                    'orderby'          => 'post_date',
                    'order'            => 'DESC',
                    'meta_key'         => '_group',
                    'meta_value'       => $anpha,
                    'post_type'        => 'contact',
                    'post_status'      => 'publish',
                    'suppress_filters' => true );
                $data = get_posts($args);  
                $arrayFavoriteContact = $this->arrayUserFavorite();  
                $contacts = array();
                foreach ($data as $objData) {
                        $id = $objData->ID;   
                        $favorite = in_array($id, $arrayFavoriteContact);
                        $contacts[] = $this->getContact( $id, $favorite);
                    }
                array_multisort($contacts, SORT_ASC);
                return $contacts;
            }    
        }

        public function getContact( $post_id, $favorite){    
                $id = $post_id;
                $data = array(
                    'firstname' => get_post_meta($id, '_firstname', true),     
                    'lastname' => get_post_meta($id, '_lastname', true),
                    'email' => get_post_meta($id, '_email', true),
                    'id' => $id,
                    'phone' => get_post_meta($id, '_phone', true),
                    'ext' => get_post_meta($id, '_ext', true),
                    'mobile' => get_post_meta($id, '_mobile', true),
                    'favorite'=> $favorite );
            return $data;
        }
        public function arrayUserFavorite(){
            $current_user = wp_get_current_user();
            $data = get_user_meta($current_user,'_userContact',false);
            return $data;
        }
        public function exportVcard(){
                # code...
            }

        }

    // end class
}